/*
 * GeoVISTA Center (Penn State, Dept. of Geography)
 * Copyright (c), 2003-2011,  Jin Chen and Alan M. MacEachren, GeoVISTA Center, Penn State University
 * All Rights Researved.
 *
 * This library is developed and distributed for free usage,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * You can redistribute and/or modify it under the terms of the
 * Simplified BSD License
 *
 *
 *
 *
 *
 *
 *
 *
 * @author: jin Chen 
 * @date: Dec 3, 2003$
 * @version: 1.0
 */
package edu.psu.geovista.app.pcp.toolkits.xml;


import edu.psu.geovista.app.pcp.toolkits.Debug;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import java.io.*;

/**
 * <p>The <code>XMLParser</code> provides several useful methods for serializing
 * W3C DOM tree into XML file and for parsing XML file into DOM tree document.</p>
 *
 * @author jin.chen@ia.com
 *
 *
 */
public class XMLParserW3C {

	/**
	 * Load DOM Document from XML file
	 *
	 * @param fileName
	 */
	public static Document loadDocument(String fileName) {
		Document doc = null;
		try {
			FileInputStream in = new FileInputStream(fileName);
			return loadDocument(in);
		} catch (Exception ex) {
			Debug.error("Can't deserialize XML file : " + fileName, ex);
		}

		return doc;
	}

	/**
	 * Save DOM Document to file
	 *
	 * @param doc 	The DOM Document to save
	 * @param fileName The file name
	 */
	public static void saveDocument(Document doc, String fileName) {
		try {
			FileOutputStream out = new FileOutputStream(new File(fileName));
			saveDocument(doc, out);
		} catch (Exception ex) {
			Debug.error("Can't serialize XML file : " + fileName, ex);
		}
	}

	/**
	 * Load DOM Document from input stream
	 *
	 * @param stream The input stream to read from.
	 */
	public static Document loadDocument(InputStream stream) {
		Document doc = null;
		try {
			DOMParser parser = new DOMParser();
			parser.parse(new InputSource(stream));
			doc = parser.getDocument();
			stream.close();
		} catch (Exception ex) {
			Debug.error("Can't deserialize XML stream. ", ex);
		}

		return doc;
	}

	/**
	 * Save DOM Document to the stream
	 *
	 * @param doc 	The DOM Document to save
	 * @param stream The output stream
	 */
	public static void saveDocument(Document doc, OutputStream stream) {
		try {
			doc.normalize();
			OutputFormat format = new OutputFormat(doc);
			format.setLineSeparator(System.getProperty("line.separator"));
			format.setIndenting(true);

			XMLSerializer serializer = new XMLSerializer(stream, format);
			serializer.serialize(doc);
			stream.flush();
			stream.close();
		} catch (Exception ex) {
			Debug.error("Can't serialize XML", ex);
		}
	}

}
